'use strict';
/**
 * require: .js .json .node
 * any -> 默认当js来解析
 */
const path = require('path');
const colors = require('colors/safe');
const semver = require('semver');
const userHome = require('user-home');
const pathExists = require('path-exists').sync;
const commander = require('commander');
const log = require('@dpx-cli-dev/log');
// const init = require('@dpx-cli-dev/init');
const exec = require('@dpx-cli-dev/exec');

const constant = require('./const');
const pkg = require('../package.json');

let args, config;

const program = new commander.Command();

async function core() {
  try {
    await prepare();
    registerCommand();
  } catch (e) {
    log.error(e.message);
    // log.verbose(e);
  }
}
function checkEnv() {
  const dotenv = require('dotenv');
  const dotenvPath = path.resolve(userHome, '.env');
  if (pathExists(dotenvPath)) {
    dotenv.config({
      path: dotenvPath,
    });
  }
  // config = createDefaultConfig(); // 第一种方案
  // log.verbose('环境变量', config);
  createDefaultConfig();
  // log.verbose('环境变量', process.env.CLI_HOME_PATH);
}
async function checkGlobalUpdate() {
  // 获取当前版本号和模块名
  const currentVersion = pkg.version;
  const npmName = pkg.name;
  // 调用npm API 获取所有版本
  const { getNpmSemverVersion } = require('@dpx-cli-dev/get-npm-info');
  const lastVersion = await getNpmSemverVersion(currentVersion, npmName);
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      colors.yellow(
        `请手动更新 ${npmName}， 当前版本：${currentVersion}，最新版本：${lastVersion}，
更新命令：npm install ${npmName}`
      )
    );
  }
  // 提取所有版本号 对比那些版本号大于当前版本
  // 给出最新的版本号 提示用户更新到该版本
}
function createDefaultConfig() {
  const cliConfig = {
    home: userHome,
  };
  if (process.env.CLI_HOME) {
    cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME);
  } else {
    cliConfig['cliHome'] = path.join(userHome, constant.DEFAULT_CLI_HOME);
  }
  process.env.CLI_HOME_PATH = cliConfig.cliHome;
  return cliConfig;
}
function checkInputArgs() {
  const minimist = require('minimist');
  args = minimist(process.argv.slice(2));
  checkArgs();
}
function checkArgs() {
  if (args.debug) {
    process.env.LOG_LEVEL = 'verbose';
  } else {
    process.env.LOG_LEVEL = 'info';
  }
  log.level = process.env.LOG_LEVEL;
}
function checkPkgVersion() {
  log.info('cli', pkg.version);
}
function checkNodeVersion() {
  const currentVersion = process.version;
  const lowestVersion = constant.LOWEST_NODE_VERSION;
  if (!semver.gte(currentVersion, lowestVersion)) {
    throw new Error(
      colors.red(`dpx-cli 需要安装 v${lowestVersion} 以上版本的 Node.js`)
    );
  }
}
function checkRoot() {
  const rootCheck = require('root-check');
  rootCheck();
}
function checkUserHome() {
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red('当前登录用户主目录不存在！'));
  }
}
function registerCommand() {
  program
    .name(Object.keys(pkg.bin)[0])
    .usage('<command [options]>')
    .version(pkg.version)
    .option('-d, --debug', '是否开启调试模式', false)
    .option('-tp, --targetPath <targetPath>', '是否指定本地调试文件路径', '');
  program
    .command('init [projectName]')
    .option('-f, --force', '是否强制初始化')
    .action(exec);
  program.on('option:debug', function () {
    const options = program.opts();
    if (options.debug) {
      process.env.LOG_LEVEL = 'verbose';
    } else {
      process.env.LOG_LEVEL = 'info';
    }
    log.level = process.env.LOG_LEVEL;
  });
  program.on('option:targetPath', function () {
    const options = program.opts();
    if (options.targetPath) {
      process.env.CLI_TARGET_PATH = options.targetPath;
    }
  });
  program.on('command:*', function (obj) {
    console.log(obj, 'obj');
    const availableCommand = program.commands.map((cmd) => cmd.name);
    console.log(colors.red('未知的命令：' + obj[0]));
    if (availableCommand.length) {
      console.log(colors.red('可用命令：' + availableCommand.join(',')));
    }
  });
  if (process.argv && program.args.length < 1) {
    // program.outputHelp();
  }
  program.parse(process.argv);
}
async function prepare() {
  checkPkgVersion();
  checkNodeVersion();
  checkRoot();
  checkUserHome();
  checkEnv();
  await checkGlobalUpdate();
}
module.exports = core;
